<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="updateVisible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form :model="dataForm" @keyup.enter="dataFormSubmit" label-width="80px">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio
            v-for="(type, index) in dataForm.typeList"
            :value="index"
            :key="index"
          >
            {{ type }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        :label="dataForm.typeList[dataForm.type] + '名称'"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          :placeholder="dataForm.typeList[dataForm.type] + '名称'"
        />
      </el-form-item>

      <el-form-item label="上级菜单" prop="parentName">
        <el-popover
          ref="menuListPopover"
          placement="bottom-start"
          trigger="click"
        >
          <el-tree
            :data="menuList"
            :props="menuListTreeProps"
            node-key="menuId"
            ref="treeRef"
            @current-change="menuListTreeCurrentChangeHandle"
            :default-expand-all="false"
            :highlight-current="true"
            :expand-on-click-node="false"
          />
          <template #reference>
            <div style="width: 200px">
              <el-input
                v-model="dataForm.parentName"
                virtual-ref="menuListPopover"
                readonly
                placeholder="点击选择上级菜单"
                class="menu-list__input"
              />
            </div>
          </template>
        </el-popover>
      </el-form-item>

      <el-form-item v-if="dataForm.type === 1" label="菜单路由" prop="url">
        <el-input v-model="dataForm.url" placeholder="菜单路由" />
      </el-form-item>

      <el-form-item v-if="dataForm.type !== 0" label="授权标识" prop="perms">
        <el-input
          v-model="dataForm.perms"
          placeholder="多个用逗号分隔, 如: user:list,user:create"
        />
      </el-form-item>

      <el-form-item v-if="dataForm.type !== 2" label="排序号" prop="orderNum">
        <el-input-number
          v-model="dataForm.orderNum"
          controls-position="right"
          :min="0"
          label="排序号"
        />
      </el-form-item>

      <el-form-item v-if="dataForm.type !== 2" label="菜单图标" prop="icon">
        <el-row>
          <el-col :span="22">
            <el-popover
              ref="iconListPopover"
              placement="bottom-start"
              trigger="click"
              popper-class="mod-menu__icon-popover"
            >
              <div class="mod-menu__icon-inner">
                <div class="mod-menu__icon-list">
                  <el-button
                    v-for="(item, index) in iconList"
                    :key="index"
                    @click="iconActiveHandle(item)"
                    :class="{ 'is-active': item === dataForm.icon }"
                  >
                    <!--                    <icon-svg :name="item" />-->
                  </el-button>
                </div>
              </div>
              <template #reference>
                <el-input
                  v-model="dataForm.icon"
                  virtual-ref="iconListPopover"
                  readonly
                  placeholder="菜单图标名称"
                  class="menu-list__input"
                />
              </template>
            </el-popover>
          </el-col>
          <el-col :span="2" class="icon-list__tips">
            <el-tooltip placement="top" effect="light">
              <template #content>
                全站推荐使用SVG Sprite, 详细请参考:
                <a
                  href="//github.com/daxiongYang/renren-fast-vue/blob/master/src/icons/index.js"
                  target="_blank"
                >
                  icons/index.js
                </a>
                描述
              </template>
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel()">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reqMenuInfo, reqMenuSelectInfo, reqMenuUpdateCommit } from '@/api/acl'
import { treeDataTranslate } from '@/utils/token.ts'

const dataForm = ref({
  id: 0,
  type: 1,
  typeList: ['目录', '菜单', '按钮'],
  name: '',
  parentId: 0,
  parentName: '',
  url: '',
  perms: '',
  orderNum: 0,
  icon: '',
  iconList: [],
})
const button = ref('添加')
const menuList = ref([])
const menuListTreeProps = ref({
  label: 'name',
  children: 'children',
})
const menuListTree = ref()
const iconList = ref<string[]>([])
defineProps(['modelValue'])

const emit = defineEmits(['update:modelValue'])

const updateVisible = (value: boolean) => {
  emit('update:modelValue', value)
}

// 处理取消按钮点击
const handleCancel = () => {
  updateVisible(false)
}

const dataFormSubmit = async () => {
  try {
    const response = await reqMenuUpdateCommit(
      dataForm.value.id > 0 ? 'update' : 'save',
      dataForm.value.id,
      dataForm.value.type,
      dataForm.value.name,
      dataForm.value.parentId,
      dataForm.value.url,
      dataForm.value.perms,
      dataForm.value.icon,
      dataForm.value.orderNum,
      dataForm.value.iconList,
    )
    if (response.code === 0) {
      ElMessage.success(`用户${button.value}成功`)
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    console.error(`用户${button.value}失败`, error)
  }
}

const init = async (id: number) => {
  button.value = id > 0 ? '修改' : '添加'
  const menu = await reqMenuSelectInfo()
  if (menu) {
    menuList.value = treeDataTranslate(menu.menuList, 'menuId')
  } else {
    ElMessage.error('菜单获取失败')
  }
  await nextTick(async () => {
    dataForm.value.id = 0
    dataForm.value.type = 1
    dataForm.value.typeList = ['目录', '菜单', '按钮']
    dataForm.value.name = ''
    dataForm.value.parentId = 0
    dataForm.value.parentName = ''
    dataForm.value.url = ''
    dataForm.value.perms = ''
    dataForm.value.orderNum = 0
    dataForm.value.icon = ''
    dataForm.value.iconList = []
    if (id > 0) {
      menuListTreeSetCurrentNode()
      try {
        const response = await reqMenuInfo(id)
        if (response.code === 0) {
          dataForm.value.id = response.menu.menuId
          dataForm.value.type = response.menu.type
          dataForm.value.name = response.menu.name
          dataForm.value.parentId = response.menu.parentId
          dataForm.value.url = response.menu.url
          dataForm.value.perms = response.menu.perms
          dataForm.value.orderNum = response.menu.orderNum
          dataForm.value.icon = response.menu.icon
          menuListTreeSetCurrentNode()
        }
      } catch (error) {
        console.error('用户信息获取失败:', error)
      }
    }
  })
}

// 菜单树设置当前选中节点
const menuListTreeSetCurrentNode = () => {
  menuListTree.value.setCurrentKey(dataForm.value.parentId)
  dataForm.value.parentName = (menuListTree.value.getCurrentNode() || {})[
    'name'
  ]
}

// 菜单树选中
const menuListTreeCurrentChangeHandle = (data: any) => {
  dataForm.value.parentId = data.menuId
  dataForm.value.parentName = data.name
}

// 图标选中
const iconActiveHandle = (iconName: any) => {
  dataForm.value.icon = iconName
}

// 暴露方法
defineExpose({ init })

onMounted(() => {
  // iconList.value = Icon.getNameList()
})
</script>

<style lang="scss"></style>
